"use client"

import { useState } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
  IconSearch,
  IconFilter,
  IconRefresh,
  IconDownload,
  IconAlertTriangle,
  IconCheck,
  IconClock,
  IconMoreVertical
} from "@tabler/icons-react"

interface MedicalDataItem {
  id: string
  type: 'alert' | 'device' | 'patient' | 'staff'
  title: string
  location: string
  status: 'active' | 'resolved' | 'pending' | 'maintenance'
  priority: 'high' | 'medium' | 'low'
  timestamp: string
  description?: string
  assignee?: string
}

// 使用静态告警数据（避免随机数）
const getStaticAlertData = () => {
  return [
    {
      id: 'ALT-001',
      type: 'alert',
      title: '急诊科人员聚集告警',
      location: '急诊科等候区',
      status: 'active',
      priority: 'high',
      timestamp: new Date(Date.now() - 15 * 60 * 1000).toLocaleString('zh-CN'),
      description: '等候区人员密度超出安全阈值',
      assignee: '张医生'
    },
    {
      id: 'ALT-002',
      type: 'device',
      title: 'MRI-01 设备维护提醒',
      location: '影像科B区',
      status: 'pending',
      priority: 'medium',
      timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000).toLocaleString('zh-CN'),
      description: '设备运行时间达到维护周期，建议安排维护',
      assignee: '技术部'
    },
    {
      id: 'ALT-003',
      type: 'alert',
      title: '手术室03温度正常',
      location: '手术室03',
      status: 'resolved',
      priority: 'low',
      timestamp: new Date(Date.now() - 4 * 60 * 60 * 1000).toLocaleString('zh-CN'),
      description: '温度传感器检测正常，环境参数稳定',
      assignee: '后勤部'
    }
  ]
}

// 模拟数据（保留作为备用）
const mockData: MedicalDataItem[] = [
  {
    id: 'ALT-001',
    type: 'alert',
    title: '急诊科人员聚集告警',
    location: '急诊科等候区',
    status: 'active',
    priority: 'high',
    timestamp: '2024-01-15 14:32:15',
    description: '等候区人员密度超出安全阈值',
    assignee: '张医生'
  },
  {
    id: 'DEV-002',
    type: 'device',
    title: 'MRI-01 设备维护',
    location: '影像科B区',
    status: 'maintenance',
    priority: 'medium',
    timestamp: '2024-01-15 13:45:22',
    description: '设备定期保养维护',
    assignee: '技术部'
  },
  {
    id: 'ALT-003',
    type: 'alert',
    title: '手术室温度异常',
    location: '手术室03',
    status: 'resolved',
    priority: 'medium',
    timestamp: '2024-01-15 12:15:08',
    description: '温度传感器检测到异常温度',
    assignee: '后勤部'
  },
  {
    id: 'DEV-004',
    type: 'device',
    title: 'CT-02 使用率过高',
    location: '影像科A区',
    status: 'pending',
    priority: 'low',
    timestamp: '2024-01-15 11:28:33',
    description: '设备连续使用超过6小时',
    assignee: '设备科'
  },
  {
    id: 'ALT-005',
    type: 'alert',
    title: '药房库存不足告警',
    location: '中心药房',
    status: 'active',
    priority: 'high',
    timestamp: '2024-01-15 10:45:12',
    description: '抗生素类药物库存低于安全线',
    assignee: '药剂科'
  }
]

const getStatusIcon = (status: string) => {
  switch (status) {
    case 'active':
      return <IconAlertTriangle className="w-4 h-4 text-error" />
    case 'resolved':
      return <IconCheck className="w-4 h-4 text-success" />
    case 'pending':
      return <IconClock className="w-4 h-4 text-warning" />
    case 'maintenance':
      return <IconClock className="w-4 h-4 text-info" />
    default:
      return null
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'active': return '活跃'
    case 'resolved': return '已解决'
    case 'pending': return '待处理'
    case 'maintenance': return '维护中'
    default: return status
  }
}

const getStatusColor = (status: string) => {
  switch (status) {
    case 'active': return 'bg-error/10 text-error border-error/20'
    case 'resolved': return 'bg-success/10 text-success border-success/20'
    case 'pending': return 'bg-warning/10 text-warning border-warning/20'
    case 'maintenance': return 'bg-info/10 text-info border-info/20'
    default: return 'bg-secondary/10 text-secondary border-secondary/20'
  }
}

const getPriorityColor = (priority: string) => {
  switch (priority) {
    case 'high': return 'bg-error/10 text-error border-error/20'
    case 'medium': return 'bg-warning/10 text-warning border-warning/20'
    case 'low': return 'bg-success/10 text-success border-success/20'
    default: return 'bg-secondary/10 text-secondary border-secondary/20'
  }
}

const getTypeIcon = (type: string) => {
  // 这里可以根据type返回不同的图标
  return type === 'alert' ? '🚨' : type === 'device' ? '🏥' : '👤'
}

interface MedicalDataTableProps {
  data?: MedicalDataItem[]
}

export function MedicalDataTable({ data }: MedicalDataTableProps) {
  // 优先使用传入的数据，否则使用真实数据，最后才用模拟数据
  const displayData = data || getStaticAlertData() || mockData
  const [searchTerm, setSearchTerm] = useState('')
  const [filterStatus, setFilterStatus] = useState<string>('all')
  const [filterType, setFilterType] = useState<string>('all')

  const filteredData = displayData.filter(item => {
    const matchesSearch =
      item.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.location.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.description?.toLowerCase().includes(searchTerm.toLowerCase())

    const matchesStatus = filterStatus === 'all' || item.status === filterStatus
    const matchesType = filterType === 'all' || item.type === filterType

    return matchesSearch && matchesStatus && matchesType
  })

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle className="flex items-center gap-2">
              医疗数据监控
            </CardTitle>
            <CardDescription>
              实时监控告警、设备状态和运营数据
            </CardDescription>
          </div>
          <div className="flex items-center space-x-2">
            <Button variant="outline" size="sm">
              <IconRefresh className="w-4 h-4 mr-2" />
              刷新
            </Button>
            <Button variant="outline" size="sm">
              <IconDownload className="w-4 h-4 mr-2" />
              导出
            </Button>
          </div>
        </div>

        {/* 搜索和筛选 */}
        <div className="flex items-center space-x-4 mt-4">
          <div className="relative flex-1 max-w-sm">
            <IconSearch className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <Input
              placeholder="搜索标题、位置或描述..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10"
            />
          </div>

          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline" size="sm">
                <IconFilter className="w-4 h-4 mr-2" />
                状态筛选
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent>
              <DropdownMenuItem onClick={() => setFilterStatus('all')}>
                全部状态
              </DropdownMenuItem>
              <DropdownMenuItem onClick={() => setFilterStatus('active')}>
                活跃
              </DropdownMenuItem>
              <DropdownMenuItem onClick={() => setFilterStatus('pending')}>
                待处理
              </DropdownMenuItem>
              <DropdownMenuItem onClick={() => setFilterStatus('resolved')}>
                已解决
              </DropdownMenuItem>
              <DropdownMenuItem onClick={() => setFilterStatus('maintenance')}>
                维护中
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>

          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline" size="sm">
                <IconFilter className="w-4 h-4 mr-2" />
                类型筛选
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent>
              <DropdownMenuItem onClick={() => setFilterType('all')}>
                全部类型
              </DropdownMenuItem>
              <DropdownMenuItem onClick={() => setFilterType('alert')}>
                告警
              </DropdownMenuItem>
              <DropdownMenuItem onClick={() => setFilterType('device')}>
                设备
              </DropdownMenuItem>
              <DropdownMenuItem onClick={() => setFilterType('patient')}>
                患者
              </DropdownMenuItem>
              <DropdownMenuItem onClick={() => setFilterType('staff')}>
                人员
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </CardHeader>

      <CardContent>
        <div className="rounded-md border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>类型</TableHead>
                <TableHead>标题</TableHead>
                <TableHead>位置</TableHead>
                <TableHead>状态</TableHead>
                <TableHead>优先级</TableHead>
                <TableHead>负责人</TableHead>
                <TableHead>时间</TableHead>
                <TableHead className="w-[50px]">操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredData.map((item) => (
                <TableRow key={item.id} className="hover:bg-muted/50">
                  <TableCell>
                    <div className="flex items-center space-x-2">
                      <span className="text-lg">{getTypeIcon(item.type)}</span>
                      <span className="text-sm text-secondary capitalize">{item.type}</span>
                    </div>
                  </TableCell>

                  <TableCell>
                    <div>
                      <div className="font-medium">{item.title}</div>
                      {item.description && (
                        <div className="text-sm text-secondary mt-1 max-w-xs truncate">
                          {item.description}
                        </div>
                      )}
                    </div>
                  </TableCell>

                  <TableCell>
                    <span className="text-sm">{item.location}</span>
                  </TableCell>

                  <TableCell>
                    <Badge variant="outline" className={`${getStatusColor(item.status)} text-xs`}>
                      <span className="flex items-center gap-1">
                        {getStatusIcon(item.status)}
                        {getStatusText(item.status)}
                      </span>
                    </Badge>
                  </TableCell>

                  <TableCell>
                    <Badge variant="outline" className={`${getPriorityColor(item.priority)} text-xs`}>
                      {item.priority === 'high' ? '高' :
                        item.priority === 'medium' ? '中' : '低'}
                    </Badge>
                  </TableCell>

                  <TableCell>
                    <span className="text-sm">{item.assignee}</span>
                  </TableCell>

                  <TableCell>
                    <span className="text-sm text-secondary">
                      {new Date(item.timestamp).toLocaleString('zh-CN')}
                    </span>
                  </TableCell>

                  <TableCell>
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button variant="ghost" size="sm">
                          <IconMoreVertical className="w-4 h-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuItem>查看详情</DropdownMenuItem>
                        <DropdownMenuItem>编辑</DropdownMenuItem>
                        <DropdownMenuItem>分配</DropdownMenuItem>
                        {item.status === 'active' && (
                          <DropdownMenuItem>标记为已解决</DropdownMenuItem>
                        )}
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>

        {filteredData.length === 0 && (
          <div className="text-center py-8 text-secondary">
            没有找到匹配的数据
          </div>
        )}

        <div className="flex items-center justify-between mt-4">
          <div className="text-sm text-secondary">
            显示 {filteredData.length} 条记录，共 {data.length} 条
          </div>
          <div className="flex items-center space-x-2">
            {/* 这里可以添加分页组件 */}
          </div>
        </div>
      </CardContent>
    </Card>
  )
} 